//
//  MHAsiNetworkItem.m
//  MHProject
//
//  Created by MengHuan on 15/4/23.
//  Copyright (c) 2015年 MengHuan. All rights reserved.
//

#import "MHAsiNetworkItem.h"
#import "AFNetworking.h"
#import "MBProgressHUD+Add.h"
#import "MHAsiNetworkDefine.h"
#import "AppDelegate.h"
@interface MHAsiNetworkItem ()

@end

@implementation MHAsiNetworkItem


#pragma mark - 创建一个网络请求项，开始请求网络
/**
 *  创建一个网络请求项，开始请求网络
 *
 *  @param networkType  网络请求方式
 *  @param url          网络请求URL
 *  @param params       网络请求参数
 *  @param delegate     网络请求的委托，如果没有取消网络请求的需求，可传nil
 *  @param hashValue    网络请求的委托delegate的唯一标示
 *  @param showHUD      是否显示HUD
 *  @param successBlock 请求成功后的block
 *  @param failureBlock 请求失败后的block
 *
 *  @return MHAsiNetworkItem对象
 */
- (MHAsiNetworkItem *)initWithtype:(MHAsiNetWorkType)networkType
                               url:(NSString *)url
                            params:(NSDictionary *)params
                          delegate:(id)delegate
                            target:(id)target
                            action:(SEL)action
                         hashValue:(NSUInteger)hashValue
                           showHUD:(BOOL)showHUD
                      successBlock:(MHAsiSuccessBlock)successBlock
                      failureBlock:(MHAsiFailureBlock)failureBlock
{
    if (self = [super init])
    {
        
//        if ([url isEqualToString:@"sms/message"]) {
//            url = @"http://114.215.135.236:8083/drugs/sms/message";
//        }else{
//            
//        }

//        url = [NSString stringWithFormat:@"%@",kBaseUrl];

        self.networkType    = networkType;
        self.url            = url;
        self.params         = params;
        self.delegate       = delegate;
        self.showHUD        = showHUD;
        self.tagrget        = target;
        self.select         = action;
        
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        if (showHUD==YES) {

            [MBProgressHUD showHUDAddedTo:app.window animated:YES];
        }
        __weak typeof(self)weakSelf = self;
        DLog(@"--请求url地址--%@\n",url);
        DLog(@"----请求参数%@\n",params);
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//        manager.requestSerializer =[AFHTTPRequestSerializer serializer];
//        [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//        [manager.requestSerializer setValue:@"text/html;charest=utf-8" forHTTPHeaderField:@"Content-Type"];
//        [manager.requestSerializer setValue:@"text/html;charest=utf-8" forHTTPHeaderField:@"Accept"];

        manager.requestSerializer =[AFJSONRequestSerializer serializer];
        [manager.requestSerializer setValue:@"Content-Type" forHTTPHeaderField:@"text/html;charest=utf-8"];
        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        manager.requestSerializer.timeoutInterval = 30.0f;
        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
//        manager.responseSerializer =[AFHTTPResponseSerializer serializer];

        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/xml", nil];

        
//        {
//            "base":{
//                "sysId":"10",
//                "userId":"1",
//                "service":"login",
//                "signature":" signature",
//                "randomNum":"randomNum",
//                "timestamp":"timestamp",
//                "bizId":" "
//            },
//            "param":{
//                "principals":"sanguo",
//                "passWord":"123qwe"
//            }
//        }
//
        
        NSString * randomNum = [NSString stringWithFormat:@"%d",10000000+arc4random()%90000000];
        NSString * pwd = [AccountHanler pwd];
        pwd = @"1234567890abc";
        NSString * timestamp = [NSString stringWithFormat:@"%.f" ,[[NSDate date] timeIntervalSince1970]*1000];
        NSString * signature = [[NSString stringWithFormat:@"%@%@%@",timestamp,randomNum,pwd] MD5String];
        NSString *userId = [AccountHanler userId];
        NSString *bizId = @"";
        NSMutableDictionary * param = [@{@"base":@{
                                                 @"sysId":@"10",
                                                 
//                                                     [NSString stringWithFormat:@"iOS%@",[[UIDevice currentDevice] systemVersion]],
                                                  @"userId":@"1",
                                                  @"service":url,
                                                  @"signature":signature,
                                                  @"randomNum":randomNum,
                                                  @"timestamp":timestamp,
                                                  @"bizId":bizId,
                                                },
                                         @"param":params
                                         } mutableCopy];
        DLog(@"%@",[param mj_JSONString]);
        
        if (networkType==MHAsiNetWorkGET)
        {
            
            [manager GET:kBaseUrl parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
                DLog(@"%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);

                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                DLog(@"\n\n----请求的返回结果 %@\n",[responseObject mj_JSONString]);

                [MBProgressHUD hideHUDForView:app.window animated:YES];
                if (successBlock) {
                    successBlock(responseObject);
                }
                if ([weakSelf.delegate respondsToSelector:@selector(requestDidFinishLoading:)]) {
                    [weakSelf.delegate requestDidFinishLoading:responseObject];
                }
                [weakSelf performSelector:@selector(finishedRequest: didFaild:) withObject:responseObject withObject:nil];
                [weakSelf removewItem];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [MBProgressHUD hideHUDForView:app.window animated:YES];
                DLog(@"---error==%@\n",error.localizedDescription);
                if (failureBlock) {
                    failureBlock(error);
                }
                if ([weakSelf.delegate respondsToSelector:@selector(requestdidFailWithError:)]) {
                    [weakSelf.delegate requestdidFailWithError:error];
                }
                [weakSelf performSelector:@selector(finishedRequest: didFaild:) withObject:nil withObject:error];
                [weakSelf removewItem];
            }];
            
        }else{
            
            [manager POST:kBaseUrl parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
                DLog(@"%lf",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);

                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                [MBProgressHUD hideHUDForView:app.window animated:YES];
                DLog(@"\n\n----请求的返回结果 %@\n",[responseObject mj_JSONString]);

                XLBaseModel *result = [XLBaseModel mj_objectWithKeyValues:responseObject];
                if (!result.resultFlag&&result.status == 209) {
                    
                    
                    [AccountHanler removeUserInfo];
                   
                    NSString *title = @"提示";
                    NSString *message = @"您的账号在别的设备进行登录，请保证自己的账号安全";
                    NSString *cancelButtonTitle = @"好的";
                    
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
                    
                    // Create the actions.
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                        
                        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                        [app setRootViewController];
                    }];
                    
                    
                    // Add the actions.
                    [alertController addAction:cancelAction];
                    [app.window.rootViewController presentViewController:alertController animated:YES completion:nil];
                    
                }else{
                    if (successBlock) {
                        successBlock(responseObject);
                    }
                    if ([weakSelf.delegate respondsToSelector:@selector(requestDidFinishLoading:)]) {
                        [weakSelf.delegate requestDidFinishLoading:responseObject];
                    }
                }
                
            
                [weakSelf performSelector:@selector(finishedRequest: didFaild:) withObject:responseObject withObject:nil];
                [weakSelf removewItem];

            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [MBProgressHUD hideAllHUDsForView:app.window animated:YES];
                DLog(@"---error==%@\n",error.localizedDescription);
                if (failureBlock) {
                    failureBlock(error);
                }
                if ([weakSelf.delegate respondsToSelector:@selector(requestdidFailWithError:)]) {
                    [weakSelf.delegate requestdidFailWithError:error];
                }
                [weakSelf performSelector:@selector(finishedRequest: didFaild:) withObject:nil withObject:error];
                [weakSelf removewItem];
                
                
                
                NSHTTPURLResponse *response = (NSHTTPURLResponse*)task.response;
                //通讯协议状态码
                NSInteger statusCode = response.statusCode;
                //服务器返回的业务逻辑报文信息
                NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
                DLog(@"errResponse--->%@",errResponse);
            }];
        }
    }
    return self;
}
/**
 *   移除网络请求项
 */
- (void)removewItem
{
    __weak typeof(self)weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([weakSelf.delegate respondsToSelector:@selector(netWorkWillDealloc:)]) {
            [weakSelf.delegate netWorkWillDealloc:weakSelf];
        }
    });
}

- (void)finishedRequest:(id)data didFaild:(NSError*)error
{
    if ([self.tagrget respondsToSelector:self.select]) {
        [self.tagrget performSelector:@selector(finishedRequest:didFaild:) withObject:data withObject:error];
    }
}

- (void)dealloc
{
    
    
}

@end

